package com.it.common.utils

import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.*
import java.util.concurrent.TimeUnit


/**
 *  @Description：
 *  @author：weishixiong
 *  @date：2023/4/18 15:44
 *
 */
object DateUtils {

    const val CHINAL_DATE_FORMATTER = "yyyy年MM月dd日 HH:mm:ss"
    const val DEFAULT_DATE_FORMATTER = "yyyy-MM-dd HH:mm:ss"
    const val DAY_DATE_FORMATTER = "yyyy-MM-dd"
    const val CHINA_DATE_FORMATTER = "yyyy年MM月dd日  HH:mm"
    const val CHINA_DAY_FORMATTER = "yyyy年MM月dd日"


    const val DEFAULT_SECOND_FORMATTER = "HH:mm:ss"

    const val DATE_FORMATTER = "yyyy/MM/dd  HH:mm:ss"

    const val MM_SS_FORMATTER = "mm:ss"
    const val TAG = "DateUtils"

    const val HH_MM_FORMATTER = "HH:mm"

    /**
     * 字符串转换成 date
     *
     * @param pattern
     * @param strDate
     * @return
     * @throws ParseException
     */
    @Throws(ParseException::class)
    fun stringToDate(pattern: String?, strDate: String?): Date? {
        val df: SimpleDateFormat
        val date: Date
        df = SimpleDateFormat(pattern)
        date = try {
            df.parse(strDate)
        } catch (pe: ParseException) {
            throw ParseException(pe.message, pe.errorOffset)
        }
        return date
    }


    /**
     * date转换成字符串
     *
     * @param destFormat
     * @param date
     * @return
     */
    fun dateToString(destFormat: String?, date: Date?): String? {
        var strDate: String? = null
        if (date != null) {
            val format = SimpleDateFormat(destFormat)
            strDate = format.format(date)
        }
        return strDate
    }

    /**
     * 秒转换分钟
     * @param seconds Int
     * @return String
     */
    fun formatMinutes(seconds: Long): String {
        val minutes = TimeUnit.SECONDS.toMinutes(seconds)
        val remainingSeconds = seconds - TimeUnit.MINUTES.toSeconds(minutes)
        return String.format("%02d:%02d", minutes, remainingSeconds)
    }

    /**
     * 秒转换小时
     * @param seconds Int
     * @return String
     */
    fun formatHour(seconds: Long): String {
        var second = seconds
        val hour = second / 3600 // 得到分钟数
        second = second % 3600 //剩余的秒数
        val minute = second / 60 //得到分
        second = second % 60 //剩余的秒
        return String.format("%02d:%02d:%02d", hour, minute, second)
    }


    fun formatMilliseconds(milliseconds: Long): String {
        val seconds = milliseconds / 1000
        val minutes = seconds / 60
        val remainingSeconds = seconds % 60

        return if (minutes > 0) {
            "${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}"
        } else {
            "${seconds.toString().padStart(2, '0')}" + "秒"
        }
    }


}